package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mapper.*;
import com.demo.pojo.entity.*;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.service.ScheduleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 排课服务实现类
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Autowired
    private ClassroomMapper classroomMapper;
    
    @Autowired
    private ClazzMapper clazzMapper;
    
    @Autowired
    private TimeSlotMapper timeSlotMapper;
    
    @Override
    public List<ScheduleListDTO> getScheduleList() {
        List<Schedule> schedules = list();
        return convertToScheduleListDTO(schedules);
    }

    @Override
    public Map<String, Object> getSchedulePage(int page, int pageSize) {
        Page<Schedule> p = new Page<>(page, pageSize);
        Page<Schedule> result = this.page(p, new QueryWrapper<Schedule>().orderByDesc("schedule_id"));
        List<ScheduleListDTO> records = convertToScheduleListDTO(result.getRecords());
        Map<String, Object> resp = new HashMap<>();
        resp.put("records", records);
        resp.put("total", result.getTotal());
        resp.put("current", result.getCurrent());
        resp.put("pages", result.getPages());
        return resp;
    }
    
    @Override
    public boolean intelligentSchedule(String semester) {
        // 调用智能排课算法服务
        return true; // 简化实现
    }
    
    @Override
    public boolean checkScheduleConflict(Schedule schedule) {
        // 检查教师时间冲突
        QueryWrapper<Schedule> teacherQuery = new QueryWrapper<>();
        teacherQuery.eq("teacher_id", schedule.getTeacherId())
                   .eq("time_slot_id", schedule.getTimeSlotId())
                   .ne("schedule_id", schedule.getScheduleId());
        long teacherConflict = count(teacherQuery);
        
        // 检查教室时间冲突
        QueryWrapper<Schedule> classroomQuery = new QueryWrapper<>();
        classroomQuery.eq("classroom_id", schedule.getClassroomId())
                     .eq("time_slot_id", schedule.getTimeSlotId())
                     .ne("schedule_id", schedule.getScheduleId());
        long classroomConflict = count(classroomQuery);
        
        return teacherConflict == 0 && classroomConflict == 0;
    }
    
    @Override
    public List<ScheduleListDTO> getTeacherSchedule(Long teacherId, String semester) {
        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId);
        // 根据学期过滤排课
        if (semester != null && !semester.isEmpty()) {
            queryWrapper.inSql("time_slot_id", "select time_slot_id from time_slot where semester = '" + semester + "'");
        }
        List<Schedule> schedules = list(queryWrapper);
        return convertToScheduleListDTO(schedules);
    }
    
    @Override
    public List<ScheduleListDTO> getClassSchedule(Long clazzId, String semester) {
        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazz_id", clazzId);
        // 根据学期过滤排课
        if (semester != null && !semester.isEmpty()) {
            queryWrapper.inSql("time_slot_id", "select time_slot_id from time_slot where semester = '" + semester + "'");
        }
        List<Schedule> schedules = list(queryWrapper);
        return convertToScheduleListDTO(schedules);
    }
    
    @Override
    public List<ScheduleListDTO> getClassroomSchedule(Long classroomId, String semester) {
        QueryWrapper<Schedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classroom_id", classroomId);
        // 根据学期过滤排课
        if (semester != null && !semester.isEmpty()) {
            queryWrapper.inSql("time_slot_id", "select time_slot_id from time_slot where semester = '" + semester + "'");
        }
        List<Schedule> schedules = list(queryWrapper);
        return convertToScheduleListDTO(schedules);
    }
    
    /**
     * 将Schedule列表转换为ScheduleListDTO列表，包含关联数据
     */
    private List<ScheduleListDTO> convertToScheduleListDTO(List<Schedule> schedules) {
        return schedules.stream()
                .map(this::convertToScheduleListDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 将单个Schedule转换为ScheduleListDTO，包含关联数据
     */
    private ScheduleListDTO convertToScheduleListDTO(Schedule schedule) {
        ScheduleListDTO dto = new ScheduleListDTO();
        BeanUtils.copyProperties(schedule, dto);
        
        // 关联查询课程信息
        if (schedule.getCourseId() != null) {
            Course course = courseMapper.selectById(schedule.getCourseId());
            if (course != null) {
                dto.setCourseName(course.getCourseName());
            }
        }
        
        // 关联查询教师信息
        if (schedule.getTeacherId() != null) {
            Teacher teacher = teacherMapper.selectById(schedule.getTeacherId());
            if (teacher != null) {
                dto.setTeacherName(teacher.getTeName());
            }
        }
        
        // 关联查询教室信息
        if (schedule.getClassroomId() != null) {
            Classroom classroom = classroomMapper.selectById(schedule.getClassroomId());
            if (classroom != null) {
                dto.setClassroomName(classroom.getClassroomName());
            }
        }
        
        // 关联查询班级信息
        if (schedule.getClazzId() != null) {
            Clazz clazz = clazzMapper.selectById(schedule.getClazzId());
            if (clazz != null) {
                dto.setClazzName(clazz.getClazzName());
            }
        }
        
        // 关联查询时间段信息
        if (schedule.getTimeSlotId() != null) {
            TimeSlot timeSlot = timeSlotMapper.selectById(schedule.getTimeSlotId());
            if (timeSlot != null) {
                dto.setSemester(timeSlot.getSemester());
                dto.setWeekNo(timeSlot.getWeekNo());
                dto.setDayOfWeek(timeSlot.getDayOfWeek());
                dto.setPeriodNo(timeSlot.getPeriodNo());
            }
        }
        
        return dto;
    }
    
    @Override
    public Long findTimeSlotId(Schedule schedule) {
        if (schedule.getWeekNo() == null || schedule.getDayOfWeek() == null || schedule.getPeriodNo() == null) {
            return null;
        }
        
        // 默认使用 advanced 学期，如果没有则使用 2025-1
        String semester = schedule.getSemester();
        if (semester == null || semester.isEmpty()) {
            semester = "advanced";
        }
        
        QueryWrapper<TimeSlot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("semester", semester)
                   .eq("week_no", schedule.getWeekNo())
                   .eq("day_of_week", schedule.getDayOfWeek())
                   .eq("period_no", schedule.getPeriodNo());
        
        TimeSlot timeSlot = timeSlotMapper.selectOne(queryWrapper);
        if (timeSlot != null) {
            return timeSlot.getTimeSlotId();
        }
        
        // 如果 advanced 学期没找到，尝试 2025-1 学期
        if (!"2025-1".equals(semester)) {
            queryWrapper.clear();
            queryWrapper.eq("semester", "2025-1")
                       .eq("week_no", schedule.getWeekNo())
                       .eq("day_of_week", schedule.getDayOfWeek())
                       .eq("period_no", schedule.getPeriodNo());
            
            timeSlot = timeSlotMapper.selectOne(queryWrapper);
            if (timeSlot != null) {
                return timeSlot.getTimeSlotId();
            }
        }
        
        return null;
    }
}




